<?php
/**
 * Order Controller is made by norman 
 * mainly for warehouse order system
 * then it modified by leo 
 * there are two order wizard  in system 
 * Order wizard to China 
 * Order wizard in china
 * 
 * There are also order wizard for shop but not completed
 * @author Norman
 *
 */
class OrderController extends Zend_Controller_Action
{
	public function indexAction(){
		
	}
	
	/**
	 * this private function is run on 126 and save result to 124
	 * it is handdling the back order which is in extra order table 
	 * it is in order wizard to china
	 * 
	 * @param unknown_type $orderOption
	 * @return multitype:
	 */
	private  function listOrderByOption($orderOption){
		//send on friday night , run on 126 , get result and send by 124
		date_default_timezone_set("Australia/Melbourne");
	
		$extOrder = new Model_DbTable_Products_Stock_Extraorder(Zend_Registry::get('db_remoteapp'));
			
		$proDes = Model_Aposinitnew::initProDes();
		$stockOld =  Model_Aposinitnew::initProBalanceAll();
	
		//1. list all Back order
	
		$arrBackOrder = array();
	
		$boList = $extOrder->getOrderByOption($orderOption);
		foreach($boList as $boRow){
	
			$key = array_search($boRow['barcode'], $arrBackOrder,true);
	
			if($key!== false){
	
				$arrBackOrder[$key + 1] = $arrBackOrder[$key + 1] + 1;
				$arrBackOrder[$key + 2] .=" , ".$boRow['shop_code'];
				$arrBackOrder[$key + 3] = $arrBackOrder[$key + 3] + $boRow['qty'];
			}
			else{
				$arrBackOrder[] = $boRow['barcode'];
				$arrBackOrder[] = 1;
				$arrBackOrder[] = $boRow['shop_code'];
				$arrBackOrder[] = $boRow['qty'];
			}
	
		}
		$arrBackOrder = array_chunk($arrBackOrder,4);
		$arrBoSort = array();
		foreach($arrBackOrder as $bk => $bv){
	
			$arrBoSort[$bk] = $bv[1];
			$desLine  = $proDes->getAposDes($bv[0]);
			$arrBackOrder[$bk][] = $desLine['DESCRIPT'];
			$stLine = $stockOld->getStockBalance($bv[0],'WH');
			$arrBackOrder[$bk][] = $stLine['BALANCE'];
		}
		array_multisort($arrBoSort,SORT_DESC,$arrBackOrder);
	
		return $arrBackOrder;
	}
	/**
	 * this is in Norman's original design , this functionis no longer use 
	 */
	public function zNOUSEsaveAddNewOrderAction(){
		$this->_helper->_layout->setLayout('layout3');
		
		$orders = new Model_DbTable_Order_Orderlist();
		$oProducts = new Model_DbTable_Order_Products();
		
		if($_POST){

			$idOrder = $orders->addOrderlist($_POST["order_id"],Model_DatetimeHelper::dateToday(), $_POST["staff_name"],$_POST["order_comm"],1);
			
			$arrProducts = unserialize(base64_decode(trim($_POST["id_products"])));
			
			foreach($arrProducts as $v){
				
			$oProducts->addProducts($idOrder, $v,0,0,0); // order qty, adjust qty , final qty				
			} 		
		}
		
	}
	/**
	 * this is in Norman's original design , this functionis no longer use
	 */
	public function saveAddExistOrderAction(){
		$this->_helper->_layout->setLayout('layout3');
	
		$orders = new Model_DbTable_Order_Orderlist();
		$oProducts = new Model_DbTable_Order_Products();
		$order = $orders->getOrderlist($_POST["id_order"]);
		$this->view->orderNo = $order["order_no"];
	
		if($_POST){
	
			//$idOrder = $orders->addOrderlist($_POST["order_id"],Model_DatetimeHelper::dateToday(), $_POST["staff_name"],$_POST["order_comm"],1);
				
			$arrProducts = unserialize(base64_decode(trim($_POST["id_products"])));
				
			foreach($arrProducts as $v){
	
				$oProducts->addProducts($_POST["id_order"], $v,0,0,0); // order qty, adjust qty , final qty
			}
		}
	
	
	}
	/**
	 * this is in Norman's original design , this functionis no longer use
	 */
	public function orderDetailAction(){
		
		$this->_helper->_layout->setLayout('layout3');
		
		$orders = new Model_DbTable_Order_Orderlist();
		$oProducts = new Model_DbTable_Order_Products();
		
		$orderNo = trim($this->_getParam("id"));
		
		$order = $orders->getOrderByNumber($orderNo);
		$this->view->order = $order;
		
		$showMessage = $this->_getParam("done");
		$this->view->showMessage = $showMessage;
		$pList = $oProducts->listProductByOrderId($order["id_order"]);
		
		$this->view->pList = $pList;
		
	}
	/**
	 * this is in Norman's original design , this functionis no longer use
	 */
	public function orderDetailPrintViewAction(){
	
		
		$orders = new Model_DbTable_Order_Orderlist();
		$oProducts = new Model_DbTable_Order_Products();
		
		$orderNo = trim($this->_getParam("id"));
		
		$order = $orders->getOrderByNumber($orderNo);
		$this->view->order = $order;		
		
		$pList = $oProducts->listProductByOrderId($order["id_order"]);
		
		$this->view->pList = $pList;		
		
	}
	/**
	 * this is in Norman's original design , this functionis no longer use
	 */
	public function orderDetailExportAction(){
		
		$this->_helper->_layout->disableLayout();
		
		$orders = new Model_DbTable_Order_Orderlist();
		$oProducts = new Model_DbTable_Order_Products();
		$products = new Model_DbTable_Productsva();
		
		
		$orderNo = trim($this->_getParam("id"));
		
		$order = $orders->getOrderByNumber($orderNo);

		$pList = $oProducts->listProductByOrderId($order["id_order"]);
		
		$arrResult = array();
		
		foreach($pList as $v){
			
			$arrtmp = array();
			$productRow = $products->getProduct($v["id_product"]);
			
			$arrtmp[] = $productRow["code_product"];
			$arrtmp[] = $productRow["title_product"];
			$arrtmp[] = $v["qty_order"];
			
			$arrResult[] = $arrtmp;
		}
		//echo "<pre>";
		//var_dump($arrResult);	
		$fl = new Model_Fileshandler();
		$fl->exportOrderExcel($orderNo, $arrResult);
		
	}
	
	/**
	 * this is in Norman's original design , this functionis no longer use
	 */
	public function addProductOrderAction(){
		
		$oProducts = new Model_DbTable_Order_Products();

		$products = new Model_DbTable_Productsva();
		
		if($_POST){
			$productCode = $_POST["product_barcode"];
			$idProduct = $products->getProductID(trim($productCode));
			$idOrder = $_POST["id_order"];
			$qty = $_POST["product_qty"];
			$oProducts->addProducts($idOrder, $idProduct, $qty, $qty,$qty);
		}
		
		$this->_redirect("/order/order-detail/done/add/id/".$_POST["order_no"]);
			
	}
	/**
	 * this is in Norman's original design , this functionis no longer use
	 */
	public function removeProductOrderAction(){
		
		if($_POST){
			
			//var_dump($_POST);
			$oProducts = new Model_DbTable_Order_Products();
			
			foreach($_POST["id_order_product"] as $k => $v){
				
				$oProducts->deleteProducts($v);
			}
		
		}
		
		$this->_redirect("/order/order-detail/done/remove/id/".$_POST["order_no"]);
	}
	
	/**
	 * this is in Norman's original design , this functionis no longer use
	 */
	public function saveOrderModifyAction(){
		
		if($_POST){
			
			//var_dump($_POST);
		
			$oProducts = new Model_DbTable_Order_Products();
				
			foreach($_POST["id_product_list"] as $k => $v){
			
				$oProducts->updateProductsQty($v, $_POST["qty".$v], $_POST["qty".$v], $_POST["qty".$v]);
			}		
			
			
		}
		
		$this->_redirect("/order/order-detail/done/save/id/".$_POST["order_no"]);
	}
	/**
	 * this is in Norman's original design , this functionis no longer use
	 */
	public function cancelOrderAction(){
		
		$this->_helper->_layout->setLayout('layout5');
		
		$order = new Model_DbTable_Order_Orderlist();
		if($_POST){

			$idOrder = $_POST["id_order"];
			
			$order->cancelOrder($idOrder);
			
		}
	
		//redirect 
		
	}
	/**
	 * this is in Norman's original design , this functionis no longer use
	 */
	public function lockOrderAction(){
		
		$order = new Model_DbTable_Order_Orderlist();
		if($_POST){
		
			$idOrder = $_POST["id_order"];
				
			$order->lockOrder($idOrder);
				
		}		
		$this->_redirect("/order/order-detail/done/lock/id/".$_POST["order_no"]);
	}
	
	/**
	 * this is in Norman's original design , this functionis no longer use
	 */
	public function orderListStatusAction(){
		
	}
	/*
	 * -----------------------Section Begin , China Order --------------------------------------
	 */
	
	
	
	/**
	 * All the order to china and in china function is modifyed by leo and norman
	 * 
	 */	
	public function importOrderToChinaAction(){
		
		// read file , to array
		// insert array to order 
		
		$arrRes = array();
		
		if($_POST){
			
			if(move_uploaded_file($_FILES['upload_file']['tmp_name'], getcwd().'/upload/'.$_FILES['upload_file']['name'])){
				
			$fl = fopen( getcwd().'/upload/'.$_FILES['upload_file']['name'], 'r');
			while(($lineData = fgetcsv($fl,1024))!=false){
				$arrRes[] = $lineData;
			}
			}
		
		
		 // code, qtyorder , 
	
		
		$cOrderDetail = new Model_DbTable_Order_Orderdetail();
		$orders = new Model_DbTable_Order_Orderlist();
		$sysConfig = new Model_DbTable_Systemconfig();
		$cot = $sysConfig->runChinaOrderCounter();
		$noOrder = 'PDWH'.Model_DatetimeHelper::dateToday('').$cot;
		
		
		foreach($arrRes as $k => $v){
			
			$codeProduct = trim($v[1]);
			$orderQty = $v[3];
			$desProduct = trim($v[2]);
			
			$qtySalesW1 = 0;
			$qtySalesW2 = 0;
			$stockShop = 0;
			$stockWh = 0;
			$statusHot = $v[0];
			$maxSoldQty = 0;
			
			if($codeProduct != '' && $codeProduct != 'Item Code' ){
				$cOrderDetail->initalorder($noOrder,'WHPC',Model_DatetimeHelper::dateToday(), $codeProduct,$qtySalesW1,$qtySalesW2, $stockShop, $stockWh, $statusHot, $orderQty, $maxSoldQty, $desProduct);
			}
		}
		
		
		$orders->addOrderlist($noOrder,Model_DatetimeHelper::dateToday(),'System','Imported Order',1);
		
		echo "<h1>Import Done</h1>";
		
		
		
		// create order no 
		// log order status 
		}
		
	}
	
	public function listChinaOrderDetailAction(){
		
		//Qu
		
		$noOrder = $this->_getParam('order_no');
		
		$cOrderDetail = new Model_DbTable_Order_Orderdetail();
		$orderList = new Model_DbTable_Order_Orderlist();
		
		$idOrderLine = $orderList->getOrderByNumber($noOrder);
		$que = new Model_DbTable_Order_Queue();
		
		
		
		if($_POST){
				
			// Add Barcode to Order
			//d($_POST);
				
			if(isset($_POST['btn_save2']) || isset($_POST['btn_save'])  ){
					
				foreach($_POST['qty_order'] as $k => $v){
		
					$cOrderDetail->reviseQty($k, $v);
				}
			}
				
			if(isset($_POST['btn_add_code'])){
		
				$codeProduct = $_POST['code_add'];
				$desProduct = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-old-apos-product-description/barcode/'.$codeProduct);
				$cOrderDetail->initalorder($noOrder,'WHPC',Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0,0,0,$_POST['is_urgent'],$_POST['qty_order'],0, $desProduct,1);
		
			}
				
			if(isset($_POST['btn_lock'])){
				// order is finalliized , disable save , can Export
				$orderList->lockOrder($idOrderLine['id_order']);
				//add product Qty into Que 
		
		
			}
				
				
		}
		
		

		$oList = $cOrderDetail->getOrderByNo($noOrder);
		
		if($_POST){
			
			if(isset($_POST['btn_lock'])){
				
				foreach($oList as $k => $v){
				$que->conditionalAddQueue($v['code_product'],$v['des_product'], $v['qty_order'],' ', 1);
				}
			}
		}
		
		$this->view->orderList = $oList;
		$this->view->idOrderLine = $idOrderLine;
		
		
		
		
	}
	
	public function listChinaOrderPrepareAction(){
		
		//Qu
		
		$noOrder = $this->_getParam('order_no');
		
		$cOrderDetail = new Model_DbTable_Order_Orderdetail();
		$orderList = new Model_DbTable_Order_Orderlist();
		
		$idOrderLine = $orderList->getOrderByNumber($noOrder);
		$que = new Model_DbTable_Order_Queue();
		
		
		
		if($_POST){
		
			// Add Barcode to Order
			//d($_POST);
		
			if(isset($_POST['btn_save2']) || isset($_POST['btn_save'])  ){
					
				foreach($_POST['qty_order'] as $k => $v){
		
					$cOrderDetail->reviseQty($k, $v);
				}
			}
		
			if(isset($_POST['btn_add_code'])){
		
				$codeProduct = $_POST['code_add'];
				$desProduct = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-old-apos-product-description/barcode/'.$codeProduct);
				$cOrderDetail->initalorder($noOrder,'WHPC',Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0,0,0,$_POST['is_urgent'],$_POST['qty_order'],0, $desProduct,1);
		
			}
		
			if(isset($_POST['btn_lock'])){
				// order is finalliized , disable save , can Export
				$orderList->lockOrder($idOrderLine['id_order']);
				//add product Qty into Que
		
		
			}
		
		
		}
		
		
		
		$oList = $cOrderDetail->getOrderByNo($noOrder);
		
		if($_POST){
				
			if(isset($_POST['btn_lock'])){
		
				foreach($oList as $k => $v){
					$que->conditionalAddQueue($v['code_product'],$v['des_product'], $v['qty_order'],' ', 1);
				}
			}
		}
		
		$this->view->orderList = $oList;
		$this->view->idOrderLine = $idOrderLine;
		
		
		
	}
	
	public function shipOrdersAction(){
		
		//get all Status 10 order 
		// change to 20 
		// In all order status = 10, find product already receieved 
		// copy received orders into order shipment detail 
		// give a shipment number , add shipp company and courier 
		
		$shipment = new Model_DbTable_Order_Shipment();
		$shipmentDetail = new Model_DbTable_Order_Shipmentdetail();
		$sysConfig = new Model_DbTable_Systemconfig();
		
		$orderDetail = new Model_DbTable_Order_Orderdetail();
		$cOrder = new Model_DbTable_Order_Orderlist();
		//Create Shipment Counter 
		$arrShipment = array();
		$arrList = array();
		
		if($_POST){
			
			$cot = $sysConfig->runChinaShipmentCounter();
			$shipmentNo = "ST".Model_DatetimeHelper::dateToday().$cot;
			
			
			$trackingNo = $_POST['tracking_no'];
			$courier = $_POST['courier_name'];
			
			// getting orders 
			// getting orders which already have received anything
			
			foreach($_POST['order_no'] as $orderNo){
				
				$oDlist = $orderDetail->receivedProductInOrder($orderNo);
				$idOrder = $cOrder->getOrderByNumber($orderNo);
				//d($oDlist);
				if($oDlist){
				$arrList = array_merge($arrList,$oDlist);
				}
				$cOrder->shipOrder($idOrder['id_order']);
			}
			
			// gathered all list , now create shipment 
			$shipment->addShipment($shipmentNo,$courier, $trackingNo,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::adjustDays("add",Model_DatetimeHelper::dateToday(),7), null,0, null);

			foreach($arrList as $v){
				$shipmentDetail->addShipmentdetail($v['no_order'],'WHPC', $v['date_order'],$v['staff_order'],$v['code_product'],$v['des_product'],$v['qty_order'], $v['status_hot'], $shipmentNo,$v['act_received'], null, null,$v['is_extra'], $v['id_supplier'],$v['box_no']);
					
			}
			
				
			
		}
		
		$this->_redirect("/order/order-list-summary");
	}
	
	/**
	 * List All Order Status 
	 */
	public function orderListSummaryAction(){
			
		$order = new Model_DbTable_Order_Orderlist();
		
		$od = new Model_DbTable_Order_Orderdetail();
		
		$shipment = new Model_DbTable_Order_Shipment();
		$shipDetail = new Model_DbTable_Order_Shipmentdetail();
		
		$que = new Model_DbTable_Order_Queue();
		
		$qList = $que->listAll();
		
		$this->view->orderActive = $orderActive = $order->listAllUnFinallizedOrder();
		
		$orderFollowUp = $order->listAllFollowUpOrder();
		
		$this->view->orderFollowUp = $orderFollowUp;
		
		$shipmentOnTheSea = $shipment->getOnTheSea();
		$arrShipOTS = array();
		
		foreach($shipmentOnTheSea as $shipmentLine){
			$orderNos = $shipDetail->orderNoInShipment($shipmentLine['shipment_no']);
			//d($orderNos);
			$orderNosAfter = array();
			foreach($orderNos as $k => $v){
				$prescent = $od->orderReadyLevel($v['no_order']);
				$orderNosAfter[] = array($v['no_order'],$prescent);
			}
			$arrShipOTS[] = array($shipmentLine,$orderNosAfter);
		}
		 
		$this->view->shipOTS = $arrShipOTS;
		
	 	$shipmentArrived = $shipment->getArrived();
	 	$arrivedAu = array();
		foreach($shipmentArrived as $shipmentLine){
			
					
			$orderNos = $shipDetail->orderNoInShipment($shipmentLine['shipment_no']);
			$orderNosAfter = array();
			foreach($orderNos as $k => $v){
				$prescent = $od->orderReadyLevel($v['no_order']);
				$orderNosAfter[] = array_merge($v,$prescent);
			}
			$arrivedAu[] = array($shipmentLine,$orderNosAfter);			
		}
		
		$this->view->arrivedAu = $arrivedAu;
		
		$this->view->orderFinished = $orderFinished = $order->listAllFinishedOrder();
		$this->view->orderCanceled = $orderCanceled = $order->listAllCanceledOrder();
		$this->view->qList = $qList;
		
	}
	
	public function printShipmentDetailAction(){
		
		$shipmentNo = $this->_getParam("shipment_no");
		$shipDetail = new Model_DbTable_Order_Shipmentdetail();

		$dList = $shipDetail->getShipmentByNo($shipmentNo);
		//d($dList);
		$arrRes = array();
		foreach($dList as $key => $v){
			//separate by box No
			$boxNo = $v['box_no'];
			if(isset($arrRes[$boxNo][$v['code_product']])){
				$arrRes[$boxNo][$v['code_product']][1] += $v['china_send'];
			}
			else{
				$arrRes[$boxNo][$v['code_product']] = array($v['des_product'],$v['china_send']);
			}
			
			
		}
		
		
		//d($arrRes);
		ksort($arrRes);
		$this->view->dList =$arrRes;
		
	}
	
	public function startScanAction(){
		// check if barcode exist 
		$codeProduct = "";
		$des = "";
		
		if($_POST){
			$codeProduct = $_POST['code_product'];
			$des = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-old-apos-product-description/barcode/".$codeProduct);
			
		}
		
		$this->view->codeProduct = $codeProduct;
		$this->view->des = $des;
		
	}
	
	public function scanChinaReceiveAction(){
		
		
		
		$cOrderDetail = new Model_DbTable_Order_Orderdetail();
		$que = new Model_DbTable_Order_Queue();
		$cOrder = new Model_DbTable_Order_Orderlist();
		$sp = new Model_DbTable_Suppliers();
		$chinaSpList = $sp->listChinaSuppliers();
		$this->view->chinaSpList = $chinaSpList;
		
		// check earliest open order 
		
		
		if($_POST){
			
			if(isset($_POST["btn_start"])){
				$this->view->codeProduct = $_POST['code_product'];
				$this->view->desProduct = $_POST['des_product'];
			}
			
			if(isset($_POST["btn_save"])){
				
				
				// if there is Locked Order then addinto it 
				$firstLockOrder = $cOrder->firstFollowUpOrder();
				
				$firstLockOrderNo ="";
				$boxOneOrderNo = '';
				
				if($firstLockOrder){

					$firstLockOrderNo = $firstLockOrder['order_no'];
				
				}
				else{
					//all order shipped there is no current Lock order 
					$sysConfig = new Model_DbTable_Systemconfig();
					$cot = $sysConfig->runChinaOrderCounter();
					$firstLockOrderNo = 'PDWH'.Model_DatetimeHelper::dateToday('').$cot;
					
					// add into the list 
					
					$cOrder->addOrderlist($firstLockOrderNo,Model_DatetimeHelper::dateToday(),"System","Add Order Since There is No Current Locking Order",10);
					
				}
				
				// End Section , if there is no locked order , add one locked order 
				d($firstLockOrderNo);
				
				// Begin to deal with first box 	
				$codeProduct = $_POST['code_product'];
				$qtyRec = $_POST['qty'];
				$boxNo = $_POST['box_no'];
				$idSupplier = $_POST['id_supplier'];
				$desProduct = $_POST['des_product'];
					
				$queExist = $que->codeExist($codeProduct); 
				
				d($queExist);
				
			
					// it is in the que , it should be in a order ,
					
					$orderLine = $cOrderDetail->getLastestOrderLineWithBox($codeProduct,$boxNo);
					$orderNo = '';
					$boxOneOrderNo = '';
					
					
					if(!$orderLine){
						
						$orderLine = $cOrderDetail->getLastestOrderLine($codeProduct);
						
						if(!$orderLine){
							$orderNo = $firstLockOrderNo;
						$boxOneOrderNo = $orderNo;
						
							
						}else{
							
							$orderNo = $orderLine['no_order'];
							$boxOneOrderNo = $orderNo;
							
						}
					}
					else{
						$orderNo = $orderLine['no_order'];
						$boxOneOrderNo = $orderNo;
						
					}
					
					if($orderLine){
						
						$orderStatusLine = $cOrder->getOrderByNumber($orderNo);
						
						if($orderStatusLine['order_status']>=10 && $orderStatusLine['order_status'] < 20 ){
							//order not shipped
							$cOrderDetail->fullFillOrder($orderLine['id_order'], $qtyRec,$idSupplier,$boxNo);
							//fullfiled the order
						}
						elseif($orderStatusLine['order_status'] >= 20){
							//pending to earliest open order
							$boxOneOrderNo = $firstLockOrderNo;
							$idNewInsert = $cOrderDetail->initalorder($firstLockOrderNo, "WHPC", Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0, 0,0,'VU',0,0, $desProduct);
							//add into it then full fill it
							$cOrderDetail->fullFillOrder($idNewInsert, $qtyRec,$idSupplier,$boxNo);
							// more than 1 box , add into list
						}
						
						
					}else{
							$idNewInsert =  $cOrderDetail->initalorder($boxOneOrderNo, "WHPC", Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0, 0,0,'VU',0,0, $desProduct);
							$cOrderDetail->fullFillOrder($idNewInsert, $qtyRec,$idSupplier,$boxNo);
						}
					
				
					
					// it is in the que, so deduce the qty in the que , if get > que , remove it from que
					
					if($queExist){
					$que->conditionalFullfillQueue($codeProduct, $qtyRec);
					}
					//reduce all Qty  , not only the first 
				
				
				
				//-------------------------------------- Same product , different box 
				
				if(trim($_POST['qty2'])!="" && trim($_POST['box_no2'])!=""){
					
					
					$codeProduct = $_POST['code_product'];
					$qtyRec = $_POST['qty2'];
					$boxNo = $_POST['box_no2'];
					$idSupplier = $_POST['id_supplier'];
					$desProduct = $_POST['des_product'];
						
					$queExist = $que->codeExist($codeProduct);
					
					
						// it is in the que , it should be in a order ,
						$orderLine = $cOrderDetail->getLastestOrderLineWithBox($codeProduct,$boxNo);
						if($orderLine){
							$orderNo = $orderLine['no_order'];
								
							$orderStatusLine = $cOrder->getOrderByNumber($orderNo);
								
							if($orderStatusLine['order_status']>=10 && $orderStatusLine['order_status'] < 20 ){
								//order not shipped
								$cOrderDetail->fullFillOrder($orderLine['id_order'], $qtyRec,$idSupplier,$boxNo);
								//fullfiled the order
							}
							elseif($orderStatusLine['order_status'] >= 20){
								//pending to earliest open order
							
								$idNewInsert = $cOrderDetail->initalorder($firstLockOrderNo, "WHPC", Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0, 0,0,'VU',0,0, $desProduct);
								//add into it then full fill it
								$cOrderDetail->fullFillOrder($idNewInsert, $qtyRec,$idSupplier,$boxNo);
								// more than 1 box , add into list
							}	
							
							
						}else{
							$idNewInsert =  $cOrderDetail->initalorder($boxOneOrderNo, "WHPC", Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0, 0,0,'VU',0,0, $desProduct);
							$cOrderDetail->fullFillOrder($idNewInsert, $qtyRec,$idSupplier,$boxNo);
						}
						
						// it is in the que, so deduce the qty in the que , if get > que , remove it from que
						if($queExist){
						$que->conditionalFullfillQueue($codeProduct, $qtyRec);
						}	
						//reduce all Qty  , not only the first
					
					
					
					
					
					
				}
				
			//-------------------------------------- Same product , different box 
				
			if(trim($_POST['qty3'])!="" && trim($_POST['box_no3'])!=""){
					
					
					$codeProduct = $_POST['code_product'];
					$qtyRec = $_POST['qty3'];
					$boxNo = $_POST['box_no3'];
					$idSupplier = $_POST['id_supplier'];
					$desProduct = $_POST['des_product'];
						
					$queExist = $que->codeExist($codeProduct);
					
					
						// it is in the que , it should be in a order ,
						$orderLine = $cOrderDetail->getLastestOrderLineWithBox($codeProduct,$boxNo);
						if($orderLine){
							$orderNo = $orderLine['no_order'];
								
							$orderStatusLine = $cOrder->getOrderByNumber($orderNo);
								
							if($orderStatusLine['order_status']>=10 && $orderStatusLine['order_status'] < 20 ){
								//order not shipped
								$cOrderDetail->fullFillOrder($orderLine['id_order'], $qtyRec,$idSupplier,$boxNo);
								//fullfiled the order
							}
							elseif($orderStatusLine['order_status'] >= 20){
								//pending to earliest open order
							
								$idNewInsert = $cOrderDetail->initalorder($firstLockOrderNo, "WHPC", Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0, 0,0,'VU',0,0, $desProduct);
								//add into it then full fill it
								$cOrderDetail->fullFillOrder($idNewInsert, $qtyRec,$idSupplier,$boxNo);
								// more than 1 box , add into list
							}	
							
							
						}else{
							$idNewInsert =  $cOrderDetail->initalorder($boxOneOrderNo, "WHPC", Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0, 0,0,'VU',0,0, $desProduct);
							$cOrderDetail->fullFillOrder($idNewInsert, $qtyRec,$idSupplier,$boxNo);
						}
						if($queExist){
						// it is in the que, so deduce the qty in the que , if get > que , remove it from que
						$que->conditionalFullfillQueue($codeProduct, $qtyRec);
							
						//reduce all Qty  , not only the first
					
					}
					
					
				}
				//----------------------box 4
				if(trim($_POST['qty4'])!="" && trim($_POST['box_no4'])!=""){
						
						
					$codeProduct = $_POST['code_product'];
					$qtyRec = $_POST['qty4'];
					$boxNo = $_POST['box_no4'];
					$idSupplier = $_POST['id_supplier'];
					$desProduct = $_POST['des_product'];
				
					$queExist = $que->codeExist($codeProduct);
						
					
						// it is in the que , it should be in a order ,
						$orderLine = $cOrderDetail->getLastestOrderLineWithBox($codeProduct,$boxNo);
						if($orderLine){
							$orderNo = $orderLine['no_order'];
				
							$orderStatusLine = $cOrder->getOrderByNumber($orderNo);
				
							if($orderStatusLine['order_status']>=10 && $orderStatusLine['order_status'] < 20 ){
								//order not shipped
								$cOrderDetail->fullFillOrder($orderLine['id_order'], $qtyRec,$idSupplier,$boxNo);
								//fullfiled the order
							}
							elseif($orderStatusLine['order_status'] >= 20){
								//pending to earliest open order
									
								$idNewInsert = $cOrderDetail->initalorder($firstLockOrderNo, "WHPC", Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0, 0,0,'VU',0,0, $desProduct);
								//add into it then full fill it
								$cOrderDetail->fullFillOrder($idNewInsert, $qtyRec,$idSupplier,$boxNo);
								// more than 1 box , add into list
							}
								
								
						}else{
							$idNewInsert =  $cOrderDetail->initalorder($boxOneOrderNo, "WHPC", Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0, 0,0,'VU',0,0, $desProduct);
							$cOrderDetail->fullFillOrder($idNewInsert, $qtyRec,$idSupplier,$boxNo);
						}
				
						// it is in the que, so deduce the qty in the que , if get > que , remove it from que
						if($queExist){
						$que->conditionalFullfillQueue($codeProduct, $qtyRec);
							
						//reduce all Qty  , not only the first
							
					}
					
						
						
						
						
				}
				
				//-----------------------box 5 
			if(trim($_POST['qty5'])!="" && trim($_POST['box_no5'])!=""){
					
					
					$codeProduct = $_POST['code_product'];
					$qtyRec = $_POST['qty5'];
					$boxNo = $_POST['box_no5'];
					$idSupplier = $_POST['id_supplier'];
					$desProduct = $_POST['des_product'];
						
					$queExist = $que->codeExist($codeProduct);
					
					
						// it is in the que , it should be in a order ,
						$orderLine = $cOrderDetail->getLastestOrderLineWithBox($codeProduct,$boxNo);
						if($orderLine){
							$orderNo = $orderLine['no_order'];
								
							$orderStatusLine = $cOrder->getOrderByNumber($orderNo);
								
							if($orderStatusLine['order_status']>=10 && $orderStatusLine['order_status'] < 20 ){
								//order not shipped
								$cOrderDetail->fullFillOrder($orderLine['id_order'], $qtyRec,$idSupplier,$boxNo);
								//fullfiled the order
							}
							elseif($orderStatusLine['order_status'] >= 20){
								//pending to earliest open order
							
								$idNewInsert = $cOrderDetail->initalorder($firstLockOrderNo, "WHPC", Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0, 0,0,'VU',0,0, $desProduct);
								//add into it then full fill it
								$cOrderDetail->fullFillOrder($idNewInsert, $qtyRec,$idSupplier,$boxNo);
								// more than 1 box , add into list
							}	
							
							
						}else{
							$idNewInsert =  $cOrderDetail->initalorder($boxOneOrderNo, "WHPC", Model_DatetimeHelper::dateToday(), $codeProduct, 0, 0, 0,0,'VU',0,0, $desProduct);
							$cOrderDetail->fullFillOrder($idNewInsert, $qtyRec,$idSupplier,$boxNo);
						}
						
						// it is in the que, so deduce the qty in the que , if get > que , remove it from que
						if($queExist){
						$que->conditionalFullfillQueue($codeProduct, $qtyRec);
							
						//reduce all Qty  , not only the first
					
					}
					
					
					
					
					
				}
				//----------------------------

			//	$this->_redirect("/order/start-scan");
			
				
				
			}
			
			
		}
		
	
		
	}
	
	public function exportGnAction(){
		
		$shipmentNo = $this->_getParam("shipment_no");
		
		$shipDetail = new Model_DbTable_Order_Shipmentdetail();
		$sDetails = $shipDetail->getShipmentByNo($shipmentNo);
		$arrRes = array();
		
		foreach($sDetails as $detailLine){
			if(isset($arrRes[$detailLine['code_product']])){
				$arrRes[$detailLine['code_product']] += $detailLine['china_send']; 
			}else{
				$arrRes[$detailLine['code_product']] = $detailLine['china_send'];
			}
		}
		
		$arrRes2 = array();
		foreach($arrRes as $k => $v){
			
			$arrRes2[] = array($k,$v);
		}
		
		$fl = new Model_Fileshandler();
		$fl->exportGn($arrRes2,"GN-".$shipmentNo);
		
		echo "<a href=\"/export/gn/GN-".$shipmentNo.".xls\" >GN-".$shipmentNo."</a>";
	}
	
	public function orderArrivedAction(){
		
		$shipment = new Model_DbTable_Order_Shipment();
		$shipmentNo = $this->_getParam("shipment_no");
		$idShipment = $shipment->getShipmentByNo($shipmentNo);
		
		$shipment->shipmentArrive($idShipment['id_shipment']);
		
		$this->_redirect("/order/order-list-summary");
	}
	
	/*
	 * -----------------------Section End , China Order --------------------------------------
	*/	

	
	public function orderWizardStep0Action(){
		
		// what is Missed this week (week end )
		$shop = $this->_getParam('shop');
		$noOrder = "PD".$shop.Model_DatetimeHelper::getThisWeekMonday('');
		$orders = new Model_DbTable_Order_Weeklyorder();
		$this->view->orderList = $orders->getOrderByNo($noOrder);
		
		//d($this->view->orderList);
		$this->view->shop = $shop;
	}
	public function orderWizardStep1Action(){
		// 
	
		
	// sold out item 
	
	}
	public function orderWizardStep2Action(){
		
		//specail order + adjustment 	
	
	
	}
	public function orderWizardSummaryAction(){
		
	}
	
	
	
	public function orderWizardTochinaPreWhorderAction(){
		set_time_limit(0);
		$dateToday = Model_DatetimeHelper::dateToday();
		$orderList = new Model_DbTable_Order_Orderlist(Zend_Registry::get('db_remoteapp'));
		$sDetail = new Model_DbTable_Roster_Stafflogindetail(Zend_Registry::get('db_remoteapp'));
		
		$date1 = Model_DatetimeHelper::getLastWeekSunday();
		$date2 = Model_DatetimeHelper::adjustDays('sub', $date1, 13);
		
		$tmD1 = explode("-" ,$date1);
		$tmD2 = explode("-", $date2);
		
		$endInv = $tmD1[1].$tmD1[2];
		$startInv = $tmD2[1].$tmD2[2];
		
		$stock = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$pResult['stock_wh'] = new Model_DbTable_Productstock(Zend_Registry::get('db_remoteapp'));
		$orderBack = new Model_DbTable_Products_Orderback(Zend_Registry::get('db_remoteapp'));
		$stkPro = Model_Aposinitnew::initProBalanceAll();
		$pSales = new Model_DbTable_Products_Sales(Zend_Registry::get('db_remoteapp'));
		
		
		
		
		$shopList = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		$this->view->dateToday = $dateToday;
		
		
		
		$shopSoldList = array();
		$soldOrderList = array();
		$backOrderList = array();
		$newItemList = array();
		$belowStockList = array();
		
		$arrNewItem = array();
		$arrBackOrder = array();
		$tmpsoldList = array();
		$tmpCleanrance = array();
		$clearanceList = array();
		
		
		$tmpLess2Week = $stock->listAllProductbyDate($date2);
		$tmpBelow = $pSales->listAll();
		
		$tmpCleanrance = $stock->clearanceList();//get clearance list
		foreach($tmpCleanrance as $k5 => $v5){
			$clearanceList[] = trim($v5['code_product']);
		}
		
		
		foreach($tmpLess2Week as $k => $v){ //get all new Items( less than 2 week)
			$arrNewItem [] = trim($v['code_product']);
		}
		
		foreach($shopList as $k => $v){
			$invApos = Model_Aposinitnew::initAposInvPro($k);
			$shopSoldList = $invApos->getPeriodSoldData($invApos::$_tbNames,$startInv,$endInv,$date1);
		
			if($shopSoldList){
				foreach ($shopSoldList as $k2 => $v2){
					$tmp = trim($v2['SCODE']);
					$tmpsoldList[] = strtoupper($tmp);
				}
			}
				
		}
		
		$tmpBackOrder = $this->listOrderByOption(1); //get all unfilled back order
		
		foreach($tmpBackOrder as $v4){
			$barcode = trim($v4[0]);
			$arrBackOrder[$barcode] = $v4[3];
		}
		
		$saleList = array_unique($tmpsoldList); //get all sold item last 2 weeks
		
		foreach($saleList as $k2 => $v2){
			if(!in_array($v2, $clearanceList)){
				if(in_array($v2, $arrNewItem )){
					$newItemList[] = trim($v2);
				}else{
					$stkLineWh = $stkPro->getStockBalance($v2,'WH');
		
					if(array_key_exists($v2, $arrBackOrder)){
						if((int)$stkLineWh['BALANCE'] < $arrBackOrder[$v2]){
							$backOrderList[$v2] = trim($arrBackOrder[$v2]); // get back order list
						}else{
							$soldOrderList[] = trim($v2); // get sold list
						}
					}else{
						$soldOrderList[] = trim($v2);
					}
				}
			}
				
		}
		foreach ($tmpBelow as $k3 => $v3){ // get all below restock level list
			$barcode = strtoupper($v3['code_product']);
		
			if($v3['result'] < 6 && $v3['result'] != '-' && $v3['result'] != 'CLS' && !in_array($barcode, $soldOrderList) && !array_key_exists($barcode,$backOrderList) && !in_array($barcode,$arrNewItem) && !in_array($barcode,$clearanceList)){
				$belowStockList[] = $barcode;
			}
		}
		
		
		
		foreach ($arrBackOrder as $k4 => $v4){ //add back order list
				
			if(!in_array($k4,$soldOrderList) && !in_array($k4,$belowStockList) && !in_array($k4, $backOrderList) && !in_array($k4,$arrNewItem) && !in_array($k4,$clearanceList)){
				$backOrderList[$k4] = $v4;
			}
				
		}
	
		
		foreach($soldOrderList as $k => $v){
			$product = $stock->getProductByBarcode($v);
			$pResult = $pSales->getSalesByCode($v);
			if($product){
			
				if($product['is_disc'] != 1){
					if($pResult['sales_w1'] != 0 && $pResult['sales_w2'] != 0){
						
						
						$stkLineWh = $stkPro->getStockBalance($v,'WH');
							
						if($stkLineWh){
							$pResult['stock_wh'] =  (int)$stkLineWh['BALANCE'];
							$pSales->updateStock($pResult['id_sales'], $pResult['stock_wh'], $pResult['stock_shop']);
						}
						$avgSales = Model_DbTable_Products_Sales::weightOrderAverage($pResult['sales_w1'] , $pResult['sales_w2'] , $pResult['sales_w3'] , $pResult['sales_w4'] , $pResult['sales_w5'] , $pResult['sales_w6'] , $pResult['sales_w7'] , $pResult['sales_w8']);
						if($avgSales > 0){
							$hold = round($pResult['stock_wh'] /$avgSales,1);
						}
						if($hold < 6){
							$orderBack->addProduct($product['id_product'], $v, 'soldlist', $dateToday);
						}
					}
			
				}
			}
		}
		
		
		foreach($backOrderList as $k => $v){
			$product = $stock->getProductByBarcode($k);
			$pResult = $pSales->getSalesByCode($k);
				if($product){
			
					if($product['is_disc'] != 1){
						$orderBack->addProduct($product['id_product'], $k, 'backorder', $dateToday , $v);
						
						if($pResult){
							$stkLineWh = $stkPro->getStockBalance($k,'WH');
							
							if($stkLineWh){
								$pResult['stock_wh'] =  (int)$stkLineWh['BALANCE'];
								$pSales->updateStock($pResult['id_sales'], $pResult['stock_wh'], $pResult['stock_shop']);
							}
						}
					}
				}
		}
		
		foreach($arrNewItem as $k => $v){
			$product = $stock->getProductByBarcode($v);
			$pResult = $pSales->getSalesByCode($v);
				if($product){
					
					if($product['is_disc'] != 1){
						$orderBack->addProduct($product['id_product'], $v, 'newItem', $dateToday);
						if($pResult){
							$stkLineWh = $stkPro->getStockBalance($k,'WH');
								
							if($stkLineWh){
								$pResult['stock_wh'] =  (int)$stkLineWh['BALANCE'];
								$pSales->updateStock($pResult['id_sales'], $pResult['stock_wh'], $pResult['stock_shop']);
							}
						}
					}
				}
		}
		
		foreach($belowStockList as $k => $v){
			$product = $stock->getProductByBarcode($v);
			$pResult = $pSales->getSalesByCode($v);
				if($product){
					
					if($product['is_disc'] != 1){
						
						if($pResult){
							$stkLineWh = $stkPro->getStockBalance($k,'WH');
								
							if($stkLineWh){
								$pResult['stock_wh'] =  (int)$stkLineWh['BALANCE'];
								$pSales->updateStock($pResult['id_sales'], $pResult['stock_wh'], $pResult['stock_shop']);
							}
						}
						$total = $pResult['sales_w1'] + $pResult['sales_w2'] + $pResult['sales_w3'] + $pResult['sales_w4'] + $pResult['sales_w5'] + $pResult['sales_w6'] + $pResult['sales_w7'] + $pResult['sales_w8'];
						if($total != 0){
							$orderBack->addProduct($product['id_product'], $v, 'below', $dateToday);
						}
					}
				}
		}
		
		foreach($clearanceList as $k => $v){
			$product = $stock->getProductByBarcode($v);
			$pResult = $pSales->getSalesByCode($v);
				if($product){
					if($product['is_disc'] != 1){
						$orderBack->addProduct($product['id_product'], $v, 'clearance', $dateToday);
						if($pResult){
							$stkLineWh = $stkPro->getStockBalance($k,'WH');
						
							if($stkLineWh){
								$pResult['stock_wh'] =  (int)$stkLineWh['BALANCE'];
								$pSales->updateStock($pResult['id_sales'], $pResult['stock_wh'], $pResult['stock_shop']);
							}
						}
					}
				}
		}


	}
	
	public function orderWizardTochinaWhorderAction(){
		$dateToday = Model_DatetimeHelper::dateToday();
		$orderList = new Model_DbTable_Order_Orderlist(Zend_Registry::get('db_remoteapp'));
		$sDetail = new Model_DbTable_Roster_Stafflogindetail(Zend_Registry::get('db_remoteapp'));
		
		$date1 = Model_DatetimeHelper::getLastWeekSunday();
		$date2 = Model_DatetimeHelper::adjustDays('sub', $date1, 13);
		
		$tmD1 = explode("-" ,$date1);
		$tmD2 = explode("-", $date2);
		
		$endInv = $tmD1[1].$tmD1[2];
		$startInv = $tmD2[1].$tmD2[2];
		
		$stock = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$pResult['stock_wh'] = new Model_DbTable_Productstock(Zend_Registry::get('db_remoteapp'));
		$orderBack = new Model_DbTable_Products_Orderback(Zend_Registry::get('db_remoteapp'));
		$stkPro = new Model_DbTable_Apos_Stock_Balanceold(Zend_Registry::get('db_allapos'));
		$pSales = new Model_DbTable_Products_Sales(Zend_Registry::get('db_remoteapp'));

		$shopList = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		$this->view->dateToday = $dateToday;
		
		$this->view->soldList = count($orderBack->getProductByCate('soldlist'));
		$this->view->backOrder = count($orderBack->getProductByCate('backorder'));
		$this->view->belowList = count($orderBack->getProductByCate('below'));
		$this->view->newItem = count($orderBack->getProductByCate('newItem'));
		$this->view->clearanceList = count($orderBack->getProductByCate('clearance'));
		
		if(isset($_POST['submit'])){
			$sysConfig = new Model_DbTable_Systemconfig();
			$cot = $sysConfig->runChinaOrderCounter();
			$orderNo = "PDWH".str_replace("-", "", $dateToday).$cot;
			$staff = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST['password'])));
			if($staff){
				  $orderList->addOrderlist($orderNo, $dateToday,$staff['ni'], $_POST['comment'], 1);

				$url = "/order/order-wizard-tochina-soldorder/orderNo/".$orderNo;
				$this->_redirect($url);
			}else{
				echo '<script>alert("Wrong Password!!");</script>';
			}
		}
		/*
		if(isset($_POST['edit'])){
			$orderNo = $_POST['order_no'];
			$orderInfo = $orderList->getOrderlistByOrderNo($orderNo);
			
			if($orderInfo['order_status'] == 1){
				$url = "http://115.64.171.97:1080/order/order-wizard-tochina-soldorder/orderNo/".$orderNo;
				$this->_redirect($url);
			}else{
				echo '<script>alert($orderNo." has locked);</script>';
			}
		}*/
		
	}
	
	
	
	
	
	public function orderWizardTochinaSoldorderAction(){
		$orderBack = new Model_DbTable_Products_Orderback(Zend_Registry::get('db_remoteapp'));
		$pSales = new Model_DbTable_Products_Sales(Zend_Registry::get('db_remoteapp'));
		$product = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$orderDetail = new Model_DbTable_Order_Orderdetail(Zend_Registry::get('db_remoteapp'));
		
		$orderNo = $this->_getParam('orderNo');
		$soldList = array();
		$tmpList = array();
		$sort = array();
		$dateToday = Model_DatetimeHelper::dateToday();
		
		
		
		$tmpList = $orderBack->getProductByCate('soldlist');
		
		foreach ($tmpList as $k => $v){
			$orderLevel = "";
			$suggetQty = 0;
			$pResult['stock_wh'] = 0;
			
			$pResult = $pSales->getSalesByCode($v['product_code']);
			$pDetail = $product->getProduct($v['product_id']);
			$tmpArr = array();
			
			$tmpArr = $v;
			if($pDetail['is_disc']!=1){
			if($pResult){
				
				$avgSales = Model_DbTable_Products_Sales::weightOrderAverage($pResult['sales_w1'] , $pResult['sales_w2'] , $pResult['sales_w3'] , $pResult['sales_w4'] , $pResult['sales_w5'] , $pResult['sales_w6'] , $pResult['sales_w7'] , $pResult['sales_w8']);
				$avgNomal = round(($pResult['sales_w1'] + $pResult['sales_w2'] + $pResult['sales_w3'] + $pResult['sales_w4'] + $pResult['sales_w5'] + $pResult['sales_w6'] + $pResult['sales_w7'] + $pResult['sales_w8'])/8,1);
				
				$tmpArr['w1'] = $pResult['sales_w1'];
				$tmpArr['w2'] = $pResult['sales_w2'];
				$tmpArr['w3'] = $pResult['sales_w3'];
				$tmpArr['w4'] = $pResult['sales_w4'];
				$tmpArr['w5'] = $pResult['sales_w5'];
				$tmpArr['w6'] = $pResult['sales_w6'];
				$tmpArr['w7'] = $pResult['sales_w7'];
				$tmpArr['w8'] = $pResult['sales_w8'];
				
				$holdWeek = "-";
				if($avgSales == 0 && ($pResult['stock_wh'] + $pResult['stock_shop'])>10){
					$holdWeek = "CLS";
				}
				// no stock no sales
				if($avgSales > 0){
				
					$holdWeek = round($pResult['stock_wh'] /$avgSales,1);
				
				}
				
				$tmpArr['avg_sales'] = $avgSales;
				$tmpArr['avg_nomal'] = $avgNomal;
				$tmpArr['wh_stock'] = $pResult['stock_wh'];
				$tmpArr['stock_shop'] = $pResult['stock_shop'];
				$tmpArr['pre_order'] = $v['order_qty'];
				$tmpArr['result'] = $holdWeek;
				if($pResult['result'] < 6){
					$tmpArr['checkStock'] = '< 6';
				}else{
					$tmpArr['checkStock'] = '> 6';
				}
				
				//if($pDetail['adj_level']){ //check adj restock level
				/*
					if($pResult['result'] <= $pDetail['adj_level'] && $pResult['result']!= 'Null' && $pResult['result'] != 'CLS' && $pResult['result'] != '-' && $pResult['result'] != 0){
						$suggetQty = round (($pResult['stock_wh']/$pResult['result']*$pDetail['adj_level'] - $pResult['stock_wh']),0);
					}elseif($pResult['result'] == 0){
						$suggetQty = round (($pResult['stock_wh']/$pResult['result']*$pDetail['adj_level'] - $pResult['stock_wh']),0);
						$tmpArr['suggest_qty'] = $suggetQty;
					}elseif($pResult['result'] == 'CLS'){
						$suggetQty = 0;
						$tmpArr['suggest_qty'] = $suggetQty;
					}
					else{
						$suggetQty = 'Null';
					}
					*/
				//}else{
					if($holdWeek <= 6 && $holdWeek != 'Null' && $holdWeek != 'CLS' && $holdWeek != '-' && $holdWeek > 0){
						$suggetQty = round (($avgNomal*9 - $pResult['stock_wh']),0);
						$tmpArr['suggest_qty'] = $suggetQty;
					}elseif($holdWeek< 0){
						$suggetQty = round (($avgNomal*9),0);
						$tmpArr['suggest_qty'] = $suggetQty;
					}elseif($holdWeek == 0){
						$suggetQty = round ($avgNomal*9,0);
						$tmpArr['suggest_qty'] = $suggetQty;
					}elseif($holdWeek == 'CLS'){
						$suggetQty = 0;
						$tmpArr['suggest_qty'] = $suggetQty;
					}
					else{
						$suggetQty = 'Null';
						$tmpArr['suggest_qty'] = $suggetQty;
					}
				//}
				
			}else{
				$tmpArr['w1'] = 'Null';
				$tmpArr['w2'] = 'Null';
				$tmpArr['w3'] = 'Null';
				$tmpArr['w4'] = 'Null';
				$tmpArr['w5'] = 'Null';
				$tmpArr['w6'] = 'Null';
				$tmpArr['w7'] = 'Null';
				$tmpArr['w8'] = 'Null';
				$tmpArr['avg_sales'] = 'Null';
				$tmpArr['avg_nomal'] = 'Null';
				$tmpArr['wh_stock'] = 'Null';
				$tmpArr['pre_order'] = 'Null';
				$tmpArr['stock_shop'] = 'Null';
				$tmpArr['result'] = '-';
				$tmpArr['suggest_qty'] = 'Null';
				$tmpArr['checkStock'] = '< 6';
			}
			
			if(!$pDetail){
				echo $v;
			}else{
				$tmpArr['description'] = $pDetail['title_product'];
			}
			$sort[] = $pResult['result'];
			$soldList[] = $tmpArr;
			}
		}
		array_multisort($sort,SORT_NUMERIC,$soldList);
		
		
		$this->view->soldList = $soldList;
		$this->view->orderNo = $orderNo;
		
		
		if(isset($_POST['next'])){
			
			foreach ($_POST['order'] as $k => $v){
				$pInfo = $product->getProduct($k);
				if($v > 0){
					//add order
					$check = $orderDetail->getOrderDetailByDateCode($pInfo['code_product'], $dateToday);
					if($check){
						$orderDetail->updateQtyOrder($check['id_order'], $v);
					}else{
						$orderDetail->initalorder($orderNo, 'WHPC', $dateToday, $pInfo['code_product'], 0, 0, 0, 0, $_POST['category'][$k], $v, null, $pInfo['title_product']);
					}
						
					if($_POST['radio'][$k] == 1){ // check discontinue
						$product->discontinueProducts($pInfo['code_product']);
					}
					if(!empty($_POST['clearance'][$k])){ //check clearance
						$product->updateProductTitle($k, "#C ".$pInfo['title_product']);
					}
						
				}else{
					if($_POST['radio'][$k] == 1){
						$product->discontinueProducts($pInfo['code_product']);
					}
					if(!empty($_POST['clearance'][$k])){
						$product->updateProductTitle($k, "#C ".$pInfo['title_product']);
					}
				}
			}
			
			
			$url = "/order/order-wizard-tochina-backorder/orderNo/".$orderNo;
			$this->_redirect($url);
			
		}
	}
	
	public function orderWizardTochinaBackorderAction(){
		$orderBack = new Model_DbTable_Products_Orderback(Zend_Registry::get('db_remoteapp'));
		$pSales = new Model_DbTable_Products_Sales(Zend_Registry::get('db_remoteapp'));
		$product = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$exOrder = new Model_DbTable_Products_Stock_Extraorder(Zend_Registry::get('db_remoteapp'));
		$orderDetail = new Model_DbTable_Order_Orderdetail(Zend_Registry::get('db_remoteapp'));
		$dateToday = Model_DatetimeHelper::dateToday();
		
		
		$backOrderList = array();
		$tmpList = array();
		$sort = array();
		$pResult['stock_wh'] = 0;
		$tmpList = $orderBack->getProductByCate('backorder');
		$orderNo = $this->_getParam('orderNo');
		
		foreach ($tmpList as $k => $v){
			$orderLevel = "";
			$suggetQty = 0;
			$pResult = $pSales->getSalesByCode($v['product_code']);
			$pDetail = $product->getProduct($v['product_id']);
			$tmpArr = array();
				
			$tmpArr = $v;
			if($pDetail['is_disc']!=1){
			if($pResult){
				
				
				$avgSales = Model_DbTable_Products_Sales::weightOrderAverage($pResult['sales_w1'] , $pResult['sales_w2'] , $pResult['sales_w3'] , $pResult['sales_w4'] , $pResult['sales_w5'] , $pResult['sales_w6'] , $pResult['sales_w7'] , $pResult['sales_w8']);
				$avgNomal = round(($pResult['sales_w1'] + $pResult['sales_w2'] + $pResult['sales_w3'] + $pResult['sales_w4'] + $pResult['sales_w5'] + $pResult['sales_w6'] + $pResult['sales_w7'] + $pResult['sales_w8'])/8,1);
				$tmpfirstOrderDate = $exOrder->getExtraorderByBarcode($v['product_code']);
				$sort2 = array();
				if($tmpfirstOrderDate){
					foreach ($tmpfirstOrderDate as $k2 => $v2){
						$sort2[] = $v2['date'];
					}
					array_multisort($sort2,SORT_DESC,$tmpfirstOrderDate);
				}
				$tmpArr['w1'] = $pResult['sales_w1'];
				$tmpArr['w2'] = $pResult['sales_w2'];
				$tmpArr['w3'] = $pResult['sales_w3'];
				$tmpArr['w4'] = $pResult['sales_w4'];
				$tmpArr['w5'] = $pResult['sales_w5'];
				$tmpArr['w6'] = $pResult['sales_w6'];
				$tmpArr['w7'] = $pResult['sales_w7'];
				$tmpArr['w8'] = $pResult['sales_w8'];
				$tmpArr['avg_sales'] = $avgSales;
				$tmpArr['avg_nomal'] = $avgNomal;
				$tmpArr['wh_stock'] = $pResult['stock_wh'];
				$tmpArr['stock_shop'] = $pResult['stock_shop'];
				
				$tmpArr['result'] = $pResult['result'];
		
				//if($pDetail['adj_level']){ //check adj restock level
				/*
				 if($pResult['result'] <= $pDetail['adj_level'] && $pResult['result']!= 'Null' && $pResult['result'] != 'CLS' && $pResult['result'] != '-' && $pResult['result'] != 0){
				$suggetQty = round (($pResult['stock_wh']/$pResult['result']*$pDetail['adj_level'] - $pResult['stock_wh']),0);
				}else{
				$suggetQty = 'Null';
				}
				*/
				//}else{
				if($tmpfirstOrderDate){
					$tmpArr['order_date'] = $tmpfirstOrderDate[0]['date'];
				}else{
					$tmpArr['order_date'] = 'Null';
				}
				
				
				
				if($avgNomal > 0){
					
					$suggetQty = round ($avgNomal*9 + $v['order_qty']- $pResult['stock_wh']- $pResult['stock_shop'],0);
					$tmpArr['suggest_qty'] = $suggetQty;
	
				}else{
					if($v['order_qty'] > 0){
						$suggetQty = $v['order_qty']+1*9;
						$tmpArr['suggest_qty'] = $suggetQty;
					}else{
						$suggetQty = 'Null';
						$tmpArr['suggest_qty'] = $suggetQty;
					}
				}
				//}
		
			}else{
				$tmpArr['w1'] = 'Null';
				$tmpArr['w2'] = 'Null';
				$tmpArr['w3'] = 'Null';
				$tmpArr['w4'] = 'Null';
				$tmpArr['w5'] = 'Null';
				$tmpArr['w6'] = 'Null';
				$tmpArr['w7'] = 'Null';
				$tmpArr['w8'] = 'Null';
				$tmpArr['avg_sales'] = 'Null';
				$tmpArr['avg_nomal'] = 'Null';
				$tmpArr['wh_stock'] = 'Null';
				$tmpArr['stock_shop'] = 'Null';
				$tmpArr['result'] = 'Null';
				$tmpArr['order_date'] = 'Null';
				$tmpArr['suggest_qty'] = 'Null';
			}
				
			if(!$pDetail){
				echo $v;
			}else{
				$tmpArr['description'] = $pDetail['title_product'];
			}
				$sort[] = $pResult['result'];
				$backOrderList[] = $tmpArr;
			}
		}
		array_multisort($sort,SORT_NUMERIC,$backOrderList);
		
		
		$this->view->backOrderList = $backOrderList;
		$this->view->orderNo = $orderNo;
		
		
		
		if(isset($_POST['next'])){
			foreach ($_POST['order'] as $k => $v){
				$pInfo = $product->getProduct($k);
				if($v > 0){
					//add order
					$check = $orderDetail->getOrderDetailByDateCode($pInfo['code_product'], $dateToday);
					if($check){
						$orderDetail->updateQtyOrder($check['id_order'], $v);
					}else{
						$orderDetail->initalorder($orderNo, 'WHPC', $dateToday, $pInfo['code_product'], 0, 0, 0, 0, $_POST['category'][$k], $v, null, $pInfo['title_product']);
					}
						
					if($_POST['radio'][$k] == 1){ // check discontinue
						$product->discontinueProducts($pInfo['code_product']);
					}
					if(!empty($_POST['clearance'][$k])){ //check clearance
						$product->updateProductTitle($k, "#C ".$pInfo['title_product']);
					}
						
				}else{
					if($_POST['radio'][$k] == 1){
						$product->discontinueProducts($pInfo['code_product']);
					}
					if(!empty($_POST['clearance'][$k])){
						$product->updateProductTitle($k, "#C ".$pInfo['title_product']);
					}
				}
			}
			
			
			$url = "/order/order-wizard-tochina-special-request/orderNo/".$orderNo;
			$this->_redirect($url);
		}
	}
	
	public function orderWizardTochinaSpecialRequestAction(){
		$orderNo = $this->_getParam('orderNo');
		$this->view->orderNo = $orderNo;
		
		if(isset($_POST['next'])){
			$url = "/order/order-wizard-tochina-belowrestock/orderNo/".$orderNo;
			$this->_redirect($url);
		}
	}
	
	public function orderWizardTochinaBelowrestockAction(){
		$orderBack = new Model_DbTable_Products_Orderback(Zend_Registry::get('db_remoteapp'));
		$pSales = new Model_DbTable_Products_Sales(Zend_Registry::get('db_remoteapp'));
		$product = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$orderDetail = new Model_DbTable_Order_Orderdetail(Zend_Registry::get('db_remoteapp'));
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$pResult['stock_wh'] = 0;
		
		$belowList = array();
		$tmpList = array();
		$sort = array();
		
		$tmpList = $orderBack->getProductByCate('below');
		$orderNo = $this->_getParam('orderNo');
		
		
		foreach ($tmpList as $k => $v){
			$pDetail = $product->getProduct($v['product_id']);
			$pResult = $pSales->getSalesByCode($v['product_code']);
			$tmpArr = array();
		
			$tmpArr = $v;
		
			if($pDetail && $pDetail['is_disc']!=1){

				if($pResult){
					
					
					$avgSales = Model_DbTable_Products_Sales::weightOrderAverage($pResult['sales_w1'] , $pResult['sales_w2'] , $pResult['sales_w3'] , $pResult['sales_w4'] , $pResult['sales_w5'] , $pResult['sales_w6'] , $pResult['sales_w7'] , $pResult['sales_w8']);
					$avgNomal = round(($pResult['sales_w1'] + $pResult['sales_w2'] + $pResult['sales_w3'] + $pResult['sales_w4'] + $pResult['sales_w5'] + $pResult['sales_w6'] + $pResult['sales_w7'] + $pResult['sales_w8'])/8,1);

					$tmpArr['w1'] = $pResult['sales_w1'];
					$tmpArr['w2'] = $pResult['sales_w2'];
					$tmpArr['w3'] = $pResult['sales_w3'];
					$tmpArr['w4'] = $pResult['sales_w4'];
					$tmpArr['w5'] = $pResult['sales_w5'];
					$tmpArr['w6'] = $pResult['sales_w6'];
					$tmpArr['w7'] = $pResult['sales_w7'];
					$tmpArr['w8'] = $pResult['sales_w8'];
					$tmpArr['avg_sales'] = $avgSales;
					$tmpArr['avg_nomal'] = $avgNomal;
					$tmpArr['description'] = $pDetail['title_product'];
					$tmpArr['register_date'] = $pDetail['date_introduce'];
					$tmpArr['supposs_level'] = 6;
					$tmpArr['current_level'] = $pResult['result'];
				/*
				if($pDetail['supposs_level']){
					$tmpArr['supposs_level'] = $pDetail['supposs_level'];
				}else{
					$tmpArr['supposs_level'] = 6;
				}*/
				}else{
					$tmpArr['w1'] = 'Null';
					$tmpArr['w2'] = 'Null';
					$tmpArr['w3'] = 'Null';
					$tmpArr['w4'] = 'Null';
					$tmpArr['w5'] = 'Null';
					$tmpArr['w6'] = 'Null';
					$tmpArr['w7'] = 'Null';
					$tmpArr['w8'] = 'Null';
					$tmpArr['avg_sales'] = 'Null';
					$tmpArr['avg_nomal'] = 'Null';
					$tmpArr['description'] = $pDetail['title_product'];
					$tmpArr['register_date'] = $pDetail['date_introduce'];
					$tmpArr['supposs_level'] = 6;
					$tmpArr['current_level'] = 'Null';
				}
				$belowList[] = $tmpArr;
				$sort[] = $pDetail['date_introduce'];
			}
			
		}
		array_multisort($sort,SORT_ASC,$belowList);
		
		$this->view->belowList = $belowList;
		$this->view->orderNo = $orderNo;
			
		if(isset($_POST['next'])){
			foreach ($_POST['order'] as $k => $v){
				$pInfo = $product->getProduct($k);
				if($v > 0){
					//add order
					$check = $orderDetail->getOrderDetailByDateCode($pInfo['code_product'], $dateToday);
					if($check){
						$orderDetail->updateQtyOrder($check['id_order'], $v);
					}else{
						$orderDetail->initalorder($orderNo, 'WHPC', $dateToday, $pInfo['code_product'], 0, 0, 0, 0, $_POST['category'][$k], $v, null, $pInfo['title_product']);
					}
						
					if($_POST['radio'][$k] == 1){ // check discontinue
						$product->discontinueProducts($pInfo['code_product']);
					}
					if(!empty($_POST['clearance'][$k])){ //check clearance
						$product->updateProductTitle($k, "#C ".$pInfo['title_product']);
					}
						
				}else{
					if($_POST['radio'][$k] == 1){
						$product->discontinueProducts($pInfo['code_product']);
					}
					if(!empty($_POST['clearance'][$k])){
						$product->updateProductTitle($k, "#C ".$pInfo['title_product']);
					}
				}
			}
			
			
			$url = "/order/order-wizard-tochina-newitems/orderNo/".$orderNo;
			$this->_redirect($url);
		}
		
	}
	public function orderWizardTochinaNewitemsAction(){
		$orderBack = new Model_DbTable_Products_Orderback(Zend_Registry::get('db_remoteapp'));
		$pSales = new Model_DbTable_Products_Sales(Zend_Registry::get('db_remoteapp'));
		$product = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$orderDetail = new Model_DbTable_Order_Orderdetail(Zend_Registry::get('db_remoteapp'));
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$newItemList = array();
		$tmpList = array();
		$sort = array();
		
		$tmpList = $orderBack->getProductByCate('newItem');
		$orderNo = $this->_getParam('orderNo');
		
		
		foreach ($tmpList as $k => $v){
			$pDetail = $product->getProduct($v['product_id']);
			$pResult = $pSales->getSalesByCode($v['product_code']);
			$tmpArr = array();
				
			$tmpArr = $v;
			
			

			if(!$pDetail){
				echo $v;
			}else{
				if($pResult){
					$tmpArr['w1'] = $pResult['sales_w1'];
					$tmpArr['w2'] = $pResult['sales_w2'];
					$tmpArr['w3'] = $pResult['sales_w3'];
					$tmpArr['w4'] = $pResult['sales_w4'];
					$tmpArr['w5'] = $pResult['sales_w5'];
					$tmpArr['w6'] = $pResult['sales_w6'];
					$tmpArr['w7'] = $pResult['sales_w7'];
					$tmpArr['w8'] = $pResult['sales_w8'];
					$tmpArr['total'] = $pResult['sales_w1'] + $pResult['sales_w2'] + $pResult['sales_w3'] + $pResult['sales_w4'] + $pResult['sales_w5'] + $pResult['sales_w6'] + $pResult['sales_w7'] + $pResult['sales_w8'];
				}else{
					$tmpArr['w1'] = 'Null';
					$tmpArr['w2'] = 'Null';
					$tmpArr['w3'] = 'Null';
					$tmpArr['w4'] = 'Null';
					$tmpArr['w5'] = 'Null';
					$tmpArr['w6'] = 'Null';
					$tmpArr['w7'] = 'Null';
					$tmpArr['w8'] = 'Null';
					$tmpArr['total'] = 'Null';
				}
				
				$tmpArr['description'] = $pDetail['title_product'];
				$tmpArr['register_date'] = $pDetail['date_introduce'];				
			}
			$newItemList[] = $tmpArr;
			$sort[] = $pDetail['date_introduce'];
		}
		array_multisort($sort,SORT_ASC,$newItemList);
		
		$this->view->newItemList = $newItemList;
		$this->view->orderNo = $orderNo;
		
		
		if(isset($_POST['next'])){
			foreach ($_POST['order'] as $k => $v){
				$pInfo = $product->getProduct($k);
				if($v > 0){
					//add order
					$check = $orderDetail->getOrderDetailByDateCode($pInfo['code_product'], $dateToday);
					if($check){
						$orderDetail->updateQtyOrder($check['id_order'], $v);
					}else{
						$orderDetail->initalorder($orderNo, 'WHPC', $dateToday, $pInfo['code_product'], 0, 0, 0, 0, $_POST['category'][$k], $v, null, $pInfo['title_product']);
			
					}
				}
			}
			
			$url = "/order/order-wizard-tochina-clearance/orderNo/".$orderNo;
			$this->_redirect($url);
		}
	}
	
	public function orderWizardTochinaClearanceAction(){
		$orderBack = new Model_DbTable_Products_Orderback(Zend_Registry::get('db_remoteapp'));
		$pSales = new Model_DbTable_Products_Sales(Zend_Registry::get('db_remoteapp'));
		$product = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$orderDetail = new Model_DbTable_Order_Orderdetail(Zend_Registry::get('db_remoteapp'));
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$newItemList = array();
		$tmpList = array();
		$sort = array();
		
		$tmpList = $orderBack->getProductByCate('clearance');
		$orderNo = $this->_getParam('orderNo');
		
		
		foreach ($tmpList as $k => $v){
			$pDetail = $product->getProduct($v['product_id']);
			$pResult = $pSales->getSalesByCode($v['product_code']);
			$tmpArr = array();
		
			$tmpArr = $v;
		
		
			if(!$pDetail){
				echo $v;
			}else{
				if($pResult){
				
					
					$tmpArr['w1'] = $pResult['sales_w1'];
					$tmpArr['w2'] = $pResult['sales_w2'];
					$tmpArr['w3'] = $pResult['sales_w3'];
					$tmpArr['w4'] = $pResult['sales_w4'];
					$tmpArr['w5'] = $pResult['sales_w5'];
					$tmpArr['w6'] = $pResult['sales_w6'];
					$tmpArr['w7'] = $pResult['sales_w7'];
					$tmpArr['w8'] = $pResult['sales_w8'];
					$tmpArr['total'] = $pResult['sales_w1'] + $pResult['sales_w2'] + $pResult['sales_w3'] + $pResult['sales_w4'] + $pResult['sales_w5'] + $pResult['sales_w6'] + $pResult['sales_w7'] + $pResult['sales_w8'];
					$tmpArr['wh_stock'] = $pResult['stock_wh'];
					$tmpArr['stock_shop'] = $pResult['stock_shop'];				
				}else{
					$tmpArr['w1'] = 'Null';
					$tmpArr['w2'] = 'Null';
					$tmpArr['w3'] = 'Null';
					$tmpArr['w4'] = 'Null';
					$tmpArr['w5'] = 'Null';
					$tmpArr['w6'] = 'Null';
					$tmpArr['w7'] = 'Null';
					$tmpArr['w8'] = 'Null';
					$tmpArr['total'] = 'Null';
					$tmpArr['wh_stock'] = 'Null';
					$tmpArr['stock_shop'] = 'Null';
				}
		
				$tmpArr['description'] = $pDetail['title_product'];
			}
			$newItemList[] = $tmpArr;
			$sort[] = $pDetail['date_introduce'];
		}
		array_multisort($sort,SORT_ASC,$newItemList);
		
		$this->view->newItemList = $newItemList;
		$this->view->orderNo = $orderNo;
		
		
		if(isset($_POST['next'])){
			foreach ($_POST['order'] as $k => $v){
				$pInfo = $product->getProduct($k);
				if($v > 0){
					//add order
					$check = $orderDetail->getOrderDetailByDateCode($pInfo['code_product'], $dateToday);
					if($check){
						$orderDetail->updateQtyOrder($check['id_order'], $v);
					}else{
						$orderDetail->initalorder($orderNo, 'WHPC', $dateToday, $pInfo['code_product'], 0, 0, 0, 0, $_POST['category'][$k], $v, null, $pInfo['title_product']);
			
					}
				}
			}
			
			$url = "/order/order-wizard-tochina-summary/orderNo/".$orderNo;
			$this->_redirect($url);
		}
	}
	
	
	public function orderWizardTochinaSummaryAction(){
		$this->_helper->layout()->disableLayout();
		
		$product = new Model_DbTable_Productsva();
		$orderDetail = new Model_DbTable_Order_Orderdetail();
		$orderList = new Model_DbTable_Order_Orderlist();
		$orderQueue = new Model_DbTable_Order_Queue();
		$pSales = new Model_DbTable_Products_Sales();
		$file = new Model_Fileshandler();
		$mail = new Model_Emailshandler();
		
		$orderNo = $this->_getParam('orderNo');
		
		$thisorderList = $orderDetail->getOrderByNo($orderNo);
		
		$this->view->orderList = $thisorderList;
		$this->view->orderNo = $orderNo;
		
		if(isset($_POST['export'])){
			
			
			foreach ($_POST['qty'] as $k => $v){
				if($v > 0){
					$orderQty = $orderDetail->getOrderdetail($k);
					if($orderQty['qty_order'] != $v){
						$orderDetail->updateQtyOrder($k, $v);
					}
				}else{
					$orderDetail->deleteOrderdetail($k);
				}
			}
			
			$orderList->lockOrderByOrderNo($orderNo);
			
			$thisorderList = $orderDetail->getOrderByNo($orderNo);
			
			if(!empty($thisorderList)){
				$list = array();
				foreach($thisorderList as $k2 => $v2){
					//$orderQueue->addQueue($v2['code_product'], $v2['des_product'], $v2['qty_order'], Model_DatetimeHelper::dateToday(), Model_DatetimeHelper::dateToday(), null, 1);
					$pInfo = $pSales->getSalesByCode($v2['code_product']);
					$list[$v2['code_product']]['des_product'] = $v2['des_product'];
					$list[$v2['code_product']]['qty_order'] = $v2['qty_order'];
					$list[$v2['code_product']]['status_hot'] = $v2['status_hot'];
					$list[$v2['code_product']]['s_w1'] = $pInfo['sales_w1'];
					$list[$v2['code_product']]['s_w2'] = $pInfo['sales_w2'];
					$list[$v2['code_product']]['s_w3'] = $pInfo['sales_w3'];
					$list[$v2['code_product']]['s_w4'] = $pInfo['sales_w4'];
					$list[$v2['code_product']]['s_w5'] = $pInfo['sales_w5'];
					$list[$v2['code_product']]['s_w6'] = $pInfo['sales_w6'];
					$list[$v2['code_product']]['s_w7'] = $pInfo['sales_w7'];
					$list[$v2['code_product']]['s_w8'] = $pInfo['sales_w8'];
					
					
				}
				$fileName = "OrderList_".$orderNo;
				$file->exportOrder($fileName, $list, $orderNo);
				echo "<br/><br/>"."<a href=\"http://".WEB_IP."/export/order/{$fileName}.xls\" >Download Order File HERE</a><br/>";
			}

			
			
			$this->view->check = true;
			
			
			
		}
		
		if(isset($_POST['exportcList'])){
			$this->_helper->layout()->disableLayout();
			$cList = array();
			
			$cList = $product->clearanceList();
			
			$this->renderScript('/products/exportCsv.phtml');
				
			$title = array('ID','Barcode','Title');

			$filename = $orderNo;
			header("Content-type: text/csv");
			header("Content-Disposition: attachment; filename={$filename}.csv");
			header("Pragma: no-cache");
			header("Expires: 0");
			$outputBuffer = fopen("php://output", 'w');
				
			fputcsv($outputBuffer,$title);

			foreach($cList as $k => $v){
				$tmpArr = array();
				$tmpArr['id'] = $v['id_product'];
				$tmpArr['code_product'] = $v['code_product'];
				$tmpArr['title'] = $v['title_product'];
				fputcsv($outputBuffer, $tmpArr);
				
				
			}
			fclose($outputBuffer);
			
		}
		
		if(isset($_POST['exportDiscontinue'])){
			$this->_helper->layout()->disableLayout();
			$dList = array();
				
			$dList = $product->discontinueList();
				
			$this->renderScript('/products/exportCsv.phtml');
			
			$title = array('ID','Barcode','Title');
			
			$filename = $orderNo;
			header("Content-type: text/csv");
			header("Content-Disposition: attachment; filename={$filename}.csv");
			header("Pragma: no-cache");
			header("Expires: 0");
			$outputBuffer = fopen("php://output", 'w');
			
			fputcsv($outputBuffer,$title);
			
			foreach($dList as $k => $v){
				$tmpArr = array();
				$tmpArr['id'] = $v['id_product'];
				$tmpArr['code_product'] = $v['code_product'];
				$tmpArr['title'] = $v['title_product'];
				fputcsv($outputBuffer, $tmpArr);
			
			
			}
			fclose($outputBuffer);
		}
	}
	
	
	public function chinaOrderWithDetailAction(){
		
		$fl = new Model_Fileshandler();
		$pro = new Model_DbTable_Productsva();
		$location = new Model_Products_Location();
		
		$arrRes = array();
		if($_POST){
			//dd($_FILES);
			if(move_uploaded_file($_FILES['upload_file']['tmp_name'],getcwd().'/'.$_FILES['upload_file']['name'])){
				$arr = $fl->excelToArray(getcwd().'/'.$_FILES['upload_file']['name']);
				//d($arr);
				foreach($arr as $k => $v){
					$strLoc = "";
					if((int)$k > 1){ // ignore the first line 
						
						$barCode = trim($v['A']);
						$des = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-old-apos-product-description/barcode/'.$barCode);
						
						if(trim($des) == 'Item Description Not Available,Please Verify Product Barcode'){

							$des = $pro->getProductNameByCode($barCode);
							
							if(!$des){$des='';}
						}
						$isNew = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/is-new-product/barcode/'.$barCode);
						$strLoc = $location->getPLByProduct(trim($barCode));
						//d($strLoc);
						$arrRes[$k]= array($isNew,$des,$strLoc);
						
					}
				}
				d($arrRes);
				// it is done write back 
				$fl->insertProductDesV1($arrRes,$_FILES['upload_file']['name']);
				
				
				
				
				
				
			}	
		}
		
	}
	/**
	 * Add by Norman on 2014-11-12
	 * 
	 */
	public function orderWizardInchinaListOfConfirmedOrderAction(){
		
		$order = new Model_DbTable_Order_Orderlist();
		
		$od = new Model_DbTable_Order_Orderdetail();
		
		$que = new Model_DbTable_Order_Queue();
		
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		$orderFollowUp = $order->listAllFollowUpOrder();
		$check = $this->_getParam('check');
		
		if($check == 'wrong'){
			echo '<script>alert("Wrong Password!!");</script>';
		}
		$qList = $que->listAll();
		
		$this->view->orderFollowUp = $orderFollowUp;
		$this->view->qList = $qList;
		
		if(isset($_POST['instock'])){
			
			$password = $_POST['password'];
			$idStaffRow = $stfDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
			if($idStaffRow){
				setcookie("staffId",$idStaffRow['id'],time() + 3600,"/order/");
				$url = "/order/order-wizard-inchina-scan-products-delivery";
				$this->_redirect($url);
			}else{
					
					
				$url = "/order/order-wizard-inchina-list-of-confirmed-order/check/wrong";
				$this->_redirect($url);
					
			}
		}
		
		if(isset($_POST['outcheck'])){
			$password = $_POST['password'];
			$idStaffRow = $stfDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
			if($idStaffRow){
				setcookie("staffId",$idStaffRow['id'],time() + 3600,"/order/");
				$url = "/order/order-wizard-inchina-scan-allocation";
				$this->_redirect($url);
			}else{
				$url = "/order-wizard-inchina-list-of-confirmed-order/check/wrong";
				$this->_redirect($url);
			}
		}
		
	}
	
	public function orderWizardInchinaConfirmedOrderDetailAction(){
		
	}
	
	/**
	 * This funcion is not temporatry
	 */
	public function orderWizardInchinaImportLockedOrderAction(){
		
		$arrRes = array();
		$cot = 0;
		
		if($_POST){
				
			if(move_uploaded_file($_FILES['upload_file']['tmp_name'], getcwd().'/upload/'.$_FILES['upload_file']['name'])){
		
				$fl = fopen( getcwd().'/upload/'.$_FILES['upload_file']['name'], 'r');
				while(($lineData = fgetcsv($fl,1024))!=false){
					if($cot >0){
					$arrRes[] = $lineData;
					}
					$cot++;
				}
				fclose($fl);
				
				$cOrderDetail = new Model_DbTable_Order_Orderdetail();
				$orders = new Model_DbTable_Order_Orderlist();
				$sysConfig = new Model_DbTable_Systemconfig();
				$orderQue = new Model_DbTable_Order_Queue();
				$cot = $sysConfig->runChinaOrderCounter();
				$noOrder = 'PDWH'.Model_DatetimeHelper::dateToday('').$cot;
				
				
				foreach($arrRes as $k => $v){
						
					$codeProduct = trim($v[1]);
					$orderQty = $v[3];
					$desProduct = trim($v[2]);
						
					$qtySalesW1 = 0;
					$qtySalesW2 = 0;
					$stockShop = 0;
					$stockWh = 0;
					$statusHot = $v[0];
					$maxSoldQty = 0;
						
					if($codeProduct != '' && $codeProduct != 'Item Code' ){
						$cOrderDetail->initalorder($noOrder,'WHPC',Model_DatetimeHelper::dateToday(), $codeProduct,$qtySalesW1,$qtySalesW2, $stockShop, $stockWh, $statusHot, $orderQty, $maxSoldQty, $desProduct);
						$orderQue->addQueue($codeProduct, $desProduct, $orderQty,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday(),'',1);
					}
				}
				
				
				$orders->addOrderlist($noOrder,Model_DatetimeHelper::dateToday(),'System','Imported Order',10);
				
				
				
				echo "<h1>Import Done</h1>";
			
			
			
			
			
			
			}
		
		}
		
		
		
	}
	
	public function orderWizardInchinaScanProductsDeliveryAction(){
		
		$codeProduct = "";
		$des = "";
		
		$isNew = false; // will show if new product 
		$showFeedback = false; // will show feedback
		
		$dateToday = Model_DatetimeHelper::dateTodayChina();
		$timeNow = Model_DatetimeHelper::timeNowChina();
		$instore = new Model_DbTable_Order_Orderstock();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		$chinaStock = new Model_DbTable_Chinastock();
		$sp = new Model_DbTable_Suppliers();
		$chinaSpList = $sp->listChinaSuppliers();
		$proVa = new Model_DbTable_Productsva();
		$que = new Model_DbTable_Order_Queue();
		
		$supplier = $this->_getParam('sup');
		$supplierOderNo = $this->_getParam('order');
		
		if($supplier){
			$this->view->supplier = $supplier;
		}
		if($supplierOderNo){
			$this->view->supplierOrder = $supplierOderNo;
		}
		
		$instoreList = $instore->getAllRecord($dateToday); //get today instore list
		//d($instoreList,$dateToday);
		
		if($_POST){
			if(!empty($_POST['code_product'])){
				$codeProduct = $_POST['code_product'];
				if(trim($codeProduct)!=''){
				    
					$title = $proVa->getProductByBarcode($codeProduct);
					if($title){
						$des = $title['title_product'];
					}
					else{
						$des = 'Item Description Not Available,Please Verify Product Barcode';
						$isNew = true;
						$showFeedback = true;
					}
				}
				
				$supplier = $_POST['id_supplier'];
				$supplierOderNo = $_POST['supplier_order_no'];
				$this->view->supplier = $supplier;
				$this->view->supplierOrder = $supplierOderNo;
			}	
			if(!empty($_POST['qty'])){
				if(isset($_POST['btn_continue'])){
					$codeProduct = $_POST['code_product'];
					$titleProduct = $_POST['description_product'];
					$supplier = $_POST['id_supplier'];
					$supplierOderNo = $_POST['supplier_order_no'];
					$qtyProduct = $_POST['qty'];
					
					$instorePerson = $_COOKIE['staffId'];
					$instoreDate = Model_DatetimeHelper::tranferToInt($dateToday.$timeNow);
					if($codeProduct){
						$stockCheck = $chinaStock->getStock($codeProduct);
						if($stockCheck){
							$chinaStock->updateStock($codeProduct, $supplier, $qtyProduct, $dateToday);
						}else{
							$chinaStock->addStock($codeProduct, $qtyProduct, $supplier, $dateToday);
						}
						
						$instore->addRecord($codeProduct, $titleProduct, $instorePerson, $qtyProduct, $instoreDate,$supplier);
						$que->conditionalFullfillQueue($codeProduct, $qtyProduct);
					}
					$url = "/order/order-wizard-inchina-scan-products-delivery/sup/".$supplier."/order/".$supplierOderNo."";
					$this->_redirect($url);
				}
			}
	
		}
	
 		$this->view->instoreList = $instoreList;
		$this->view->codeProduct = $codeProduct;
		$this->view->des = $des;
		$this->view->isNew = $isNew;
		$this->view->showFeedback = $showFeedback;
		$this->view->chinaSpList = $chinaSpList;
		
		
	}
	public function orderWizardInchinaScanAllocationAction(){
		
		$cOrderDetail = new Model_DbTable_Order_Orderdetail();
		$que = new Model_DbTable_Order_Queue();
		$cOrder = new Model_DbTable_Order_Orderlist();
		$product = new Model_DbTable_Productsva();
		$instore = new Model_DbTable_Order_Orderstock();
		$shipDetail = new Model_DbTable_Order_Shipmentdetail();
		$dateOrder = Model_DatetimeHelper::dateTodayChina();
		
		$sp = new Model_DbTable_Suppliers();
		$chinaSpList = $sp->listChinaSuppliers();
		$this->view->chinaSpList = $chinaSpList;
		$noBarcodeList = array();
		
		$tOrderNo = $this->_getParam('orderNo');
		
		$dateToday = Model_DatetimeHelper::dateTodayChina();
		$timeNow = Model_DatetimeHelper::timeNowChina();
		
		if(isset($_POST['save'])){
			$boxNo = $_POST['boxNo'];
			$orderNo = $_POST['orderNo'];
			foreach ($_POST['barcode'] as $k => $v){
				$tmpArr = array();
				$qty = $_POST['qty'][$k];
				$pOrderDetail = $cOrderDetail->barcodeExistInOrder($v, $orderNo);
				if($pOrderDetail && !empty($boxNo)){

				$shipDetail->addShipmentdetail($orderNo, $pOrderDetail['shop_code'], $dateOrder,1, $v, $pOrderDetail['des_product'], $qty, $pOrderDetail['status_hot'], null, $pOrderDetail['qty_order'], null, null, null, null, $boxNo);
				}else{
					$tmpArr['barcode'] = $v;
					$tmpArr['qty'] = $qty;
					$noBarcodeList[$boxNo][] = $tmpArr;
				}
			}
		
			$this->view->orderNo = $orderNo;
			$this->view->noBarcodeList = $noBarcodeList;
		}
	
	}
	
	public function orderWizardInchinaSummaryAction(){
		$shipDetail = new Model_DbTable_Order_Shipmentdetail();
		$orderNo = $this->_getParam('orderNo');
		
		if($orderNo){
			$tmpShipList = $shipDetail->getShipmentByOrderNo($orderNo);
			$shipList = array();
			$totalList = array();
		
			if($tmpShipList){
				foreach ($tmpShipList as $k => $v){
					$shipList[$v['box_no']][] = $v;
					if(isset($totalList[$v['code_product']])){
					$totalList[$v['code_product']] += $v['china_send'];
					}
					else{
						$totalList[$v['code_product']] = $v['china_send'];
					}
				}
			}
	
		$this->view->list = $shipList;
		$this->view->totalList = $totalList;
		$this->view->orderNo = $orderNo;
		}
	}
	
	
	public function orderWizardInchinaPrepareShipmentAction(){
		$orderDetail = new Model_DbTable_Order_Orderdetail();
		$orderList = new Model_DbTable_Order_Orderlist();
		
		
	}
	public function orderWizardInchinaConfirmShipmentAction(){
		$tOrderNo = $this->_getParam('orderNo');
		$this->view->orderNo = $tOrderNo;
	}
	public function orderWizardInchinaShippedExportAction(){
		$shipment = new Model_DbTable_Order_Shipment();
		$shipDetail = new Model_DbTable_Order_Shipmentdetail();
		$dateToday = Model_DatetimeHelper::dateTodayChina();
		$hour = Model_DatetimeHelper::timeNowChina();
		
		if($_POST){
			
			$shipList = $shipDetail->getShipmentByOrderNo($_POST['order_no']);
			if($shipList){
				
				$shipmentNo = 'ST'.$dateToday.date("H",strtotime($hour));
				$idShipment = $shipment->addShipment($shipmentNo, null, null, $dateToday, null, null, 0, null);
				foreach ($shipList as $k => $v){
					$shipDetail->updateShipmentNo($v['id_order'], $shipmentNo);
				}

				$shipment->updateCourier($idShipment, $_POST['name_courier'], $_POST['track_no']);
		
			}
		}
	}
	
	/**
	 * After Order Change Into Shipment , it is Show in AU
	 */
	public function orderWizardToAustraliaSummaryOfShipmentAction(){
		
	}
	public function orderWizardToAustraliaExportGrnAction(){
		
	}
	public function orderWizardToAustraliaExportDeliveryNotesAction(){
		
		
		   
	}
}
?>